package com.tjetc.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.tjetc.StartMain;
import org.apache.commons.dbutils.BasicRowProcessor;
import org.apache.commons.dbutils.GenerousBeanProcessor;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.RowProcessor;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @Author: itda
 * @Date: 2024/5/9 17:24
 * @Description: DruidUtils
 */
public class DruidUtils {
    private static DataSource dataSource;
    public static RowProcessor rowProcessor=new BasicRowProcessor(new GenerousBeanProcessor());

    static {
        try {
            //创建Properties对象
            Properties properties = new Properties();
            //得到配置文件的输入流
            InputStream inputStream = StartMain.class.getClassLoader().getResourceAsStream("db.properties");
            //调用Properties对象的方法加载输入流
            properties.load(inputStream);
            ///调用druid的api将Properties对象作为方法的参数创建数据库连接池, dataSource就是数据库连接池
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 无参构造 用于增删改
     */
    public static QueryRunner r1 = new QueryRunner();
    /**
     * 有参构造 用于查询
     */
    public static QueryRunner r2 = new QueryRunner(dataSource);
    private static ThreadLocal<Connection> local = new ThreadLocal<>();
    public static Connection getConnection(){
        try {
            Connection connection = local.get();
            if (connection==null){
                connection = dataSource.getConnection();
                local.set(connection);
            }
            return connection;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 开启事务
     */
    public static void start(){
        try {
            getConnection().setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 提交事务
     */
    public static void commit(){
        try {
            getConnection().commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 回滚事务
     */
    public static void rollback(){
        try {
            getConnection().rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭事务 移除TreadLocal值
     */
    public static void close(){
        try {
            getConnection().close();
            local.remove();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
